//安卓裁剪照片类
import common from './common.js'
const Intent = plus.android.importClass('android.content.Intent');
const MediaStore = plus.android.importClass('android.provider.MediaStore');
const File = plus.android.importClass('java.io.File');
const Uri = plus.android.importClass('android.net.Uri');
const sysInfo = uni.getSystemInfoSync();
export default {
	// 进入相机
	enterCamera(callback) {
		plus.camera.getCamera(1).captureImage(
			filePath => {
				this.cropPhoto(Uri.parse(`file://${plus.io.convertLocalFileSystemURL(filePath)}`), callback);
			}, null, {
				filename: '_doc/camera/',
				optimize: false
			}
		);
	},
	//进入相册
	enterGallery(callback) {
		const intent = new Intent(Intent.ACTION_PICK);
		intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
		const main = plus.android.runtimeMainActivity();
		main.onActivityResult = (requestCode, resultCode, data) => {
			if (resultCode == -1) {
				this.cropPhoto(data.getData(), callback);
			}
		};
		main.startActivityForResult(intent, 1);
	},
	//图片临时保存路径
	imageTempPath() {
		return `_doc/Avatar/${common.formatDate(new Date(),'yyyyMMddhhmmssS')}.jpg`;
	},
	//裁剪照片
	cropPhoto(uri, callback) {
		const IMAGE_UNSPECIFIED = 'image/*';
		const PHOTOZOOM = 2; // 获取完图片返回key
		const PHOTOLAT = 1; // 剪裁完毕后返回key
		const main = plus.android.runtimeMainActivity();
		const outRelativePath = this.imageTempPath(); //返回的相对路径
		const outPutPath = plus.io.convertLocalFileSystemURL(outRelativePath);
		// 输出目录uri
		const outPutUri = Uri.fromFile(new File(outPutPath));
		// const uri = Uri.parse(filepath);
		const cropIntent = new Intent('com.android.camera.action.CROP');
		cropIntent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		// 截图完毕后 输出目录
		cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri);
		cropIntent.putExtra('crop', 'true');
		//华为会变圆形，特殊处理
		if (sysInfo.brand.includes("HUAWEI")) {
			cropIntent.putExtra("aspectX", 9998);
			cropIntent.putExtra("aspectY", 9999);
		} else {
			cropIntent.putExtra("aspectX", 1);
			cropIntent.putExtra("aspectY", 1);
		}
		// outputX outputY 是裁剪图片宽高
		cropIntent.putExtra('outputX', 390);
		cropIntent.putExtra('outputY', 390);
		cropIntent.putExtra('return-data', false);
		main.onActivityResult = (requestCode, resultCode, data) => {
			if (requestCode == PHOTOLAT && callback) {
				// 判断 剪裁完后的图片输出是否存在
				const file = new File(outPutPath);
				callback({
					success: file.exists(),
					filePath: outRelativePath
				});
			}
		};
		main.startActivityForResult(cropIntent, PHOTOLAT);
	}
}
